package com.ndf.learn.common;

import org.apache.commons.lang.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author : linchengjun
 * @Description: Ip转换为Long工具类
 * @date : 2018-10-09 10:15
 *
 * 由于Int类型的范围 -2147483648 ~ 2147483647；而IP地址的最大可能值为4294967295（255.255.255.255转换而来）
 * 所以不采用Int存储，而采用Long类型
 *
 * https://blog.csdn.net/just4you/article/details/70767928
 * https://blog.csdn.net/q472599451/article/details/8237535
 * https://blog.csdn.net/shanliangliuxing/article/details/12713881
 */
public class IpLongConverter {

    /**
     * 将ip地址转换为long
     * 1.正则表达式判断IP地址是否格式正确
     * 2.提取元素按位运算
     */
    public static long ip2Long(String ip) {
        if (StringUtils.isBlank(ip)) {
            return 0L;
        }
        String reg = "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(ip);
        if (matcher.find()) {
            return Long.valueOf(matcher.group(1)) << 24
                    | Long.valueOf(matcher.group(2)) << 16
                    | Long.valueOf(matcher.group(3)) << 8
                    | Long.valueOf(matcher.group(4));
        }
        return 0L;
    }

    /**
     * 将long转换为ip地址
     */
    public static String long2ip(long ipLong) {
        if (ipLong <= 0) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        sb.append((ipLong >> 24) & 0xFF).append(".");
        sb.append((ipLong >> 16) & 0xFF).append(".");
        sb.append((ipLong >> 8) & 0xFF).append(".");
        sb.append(ipLong & 0xFF);
        return sb.toString();
    }

    public static void main(String[] args) {
        String ip = "255.255.255.255";
        long val = IpLongConverter.ip2Long(ip);
        System.out.println(val);

        String r = IpLongConverter.long2ip(val);
        System.out.println(r);
    }

}
